#include "ModifiUserPasswd.h"
#include "ui_ModifiUserPasswdForm.h"
#include <QDebug>
#include "Auxiliary/View/MessageBoxDialog.h"
#include <QSqlRecord>


ModifiUserPasswd::ModifiUserPasswd(int ID, MySqlTableModel *model, QWidget *parent) :
    QDialog(parent), model(model),
    m_ID(ID),
    ui(new Ui::ModifiUserPasswd)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);

    QSqlRecord record = model->record(m_ID);

    if(record.isEmpty() || record.contains("passwd") == false)
    {
        qDebug()<<"record is empty or field is not exist in this record";
        return;
    }

    oldPasswd = record.value("passwd").toString();
}

ModifiUserPasswd::~ModifiUserPasswd()
{
    delete ui;
}

void ModifiUserPasswd::on_Btn_OK_clicked()
{
    newpasswd = ui->en_lineEdit_newpasswd->text();
    verifypasswd = ui->en_lineEdit_verifypasswd->text();
    if(oldPasswd == ui->en_lineEdit_oldpasswd->text())
    {
        if(newpasswd != verifypasswd)
        {
            MessageBoxDialog *messageBox = new MessageBoxDialog(this,\
                                     QString(tr("两次输入密码不一致。")));
            messageBox->exec();

        }
        else
        {
            QString passwd = ui->en_lineEdit_newpasswd->text();

            QSqlRecord record = model->record(m_ID);

            if(record.isEmpty() || record.contains("passwd") == false)
            {
                qDebug()<<"record is empty or field is not exist in this record";
                return;
            }

            record.setValue("passwd", passwd);
            model->setRecord(m_ID, record);

            // 开始事物操作
            model->database().transaction();

            if(model->submitAll())
            {
                model->database().commit();   //提交
                emit destroy();
            }
            else
            {
                model->database().rollback();  //回滚
            }

            close();
        }
    }
    else
    {
        MessageBoxDialog *messageBox = new MessageBoxDialog(this,\
                                 QString(tr("旧密码输入无效。")));
        messageBox->exec();
    }

}

void ModifiUserPasswd::on_Btn_cancel_clicked()
{
    close();
}
